#include "keyboard.h"
#include "ui_keyboard.h"

Keyboard::Keyboard(Game* game, QWidget *parent) :
	QFrame(parent), game_(game),
    ui(new Ui::Keyboard)
{
	ui->setupUi(this);

	// Setup images
	pics_.append(new QPixmap(":/images/empty.png"));
	pics_.append(new QPixmap(":/images/circle.png"));
	pics_.append(new QPixmap(":/images/cross.png"));

	// Setup labels (locations) on a grid layout
	size_ = game_->boardSize();
	locs_.clear();
	for( int i=0; i<size_.width(); i++ )
	{
		// Add a vertical layout
		QVBoxLayout * vlay = new QVBoxLayout();
		ui->hLayout->addLayout(vlay);
		locs_.append( QVector<Location*>() );
		for( int j=0; j<size_.height(); j++ ) // for every row
		{
			// Create a Location
			locs_[i].append( new Location() );
			Location* l = locs_[i][j];
			vlay->addWidget(l,1,Qt::AlignCenter);
			l->setPixmap( *(pics_[0]) );
			l->setScaledContents(true);
			connect( l, SIGNAL(clicked(Location*)),
					 this, SLOT(updateLocation(Location*)) );

			// Draw horizontal lines between rows
			if( j < size_.height()-1 )
			{
				QFrame* hline = new QFrame();
				hline->setFrameShape(QFrame::HLine);
				hline->setFrameShadow(QFrame::Sunken);
				vlay->addWidget(hline);
			}
		}

		// Draw vertical lines between columns
		if( i < size_.width()-1 )
		{
			QFrame* vline = new QFrame();
			vline->setFrameShape(QFrame::VLine);
			vline->setFrameShadow(QFrame::Sunken);
			ui->hLayout->addWidget(vline);
		}
	}
}

Keyboard::~Keyboard()
{
    delete ui;
}


void Keyboard::updateLocation( Location* l )
{
	if( l->value() ) // if location had already been touch
		return;      // then do nothing

	int player = game_->currentPlayer();
	l->value( player );
	l->setPixmap( *(pics_[player]) );
	emit keyboardUpdated(this);
}
